import Header from '@/components/layouts/Header';
import ProLayout, { PageContainer } from '@ant-design/pro-layout';
import routes, { independentRoutes } from '@/../config/router';
import { NavLink, useLocation, matchPath, history } from 'umi';
import { Tabs } from 'antd';
import { useEffect, useRef, useState, useContext, createContext } from 'react';
import { TabsProps } from 'antd/lib/tabs';

/**
 * 将tab栏的控制权下放
 */
interface PageTableAction {
    removeCurrentTab: () => void;
}
export const PageTabActionContext = createContext<PageTableAction>(
    {} as PageTableAction,
);

interface TabImte {
    tab: string;
    title: string;
}

function Index(props: any) {
    /** 独立页面需要过滤，使其不被proLayout包裹 */
    const location = useLocation();
    const user = localStorage.user;
    const isIndenpendentRoute = independentRoutes.some((item: any) => {
        const match = matchPath(location.pathname, item);
        return match?.isExact;
    });

    const [tabList, setTabList] = useState<TabImte[]>([]);
    const [active, setActive] = useState<string>();
    const tableCacheRef = useRef(new Map());
    const pathname = props.location.pathname;

    const renderChildren = (item: typeof tabList[number]) => {
        const map = tableCacheRef.current;
        return map.get(item.tab);
    };

    const removeTabHandler: TabsProps['onEdit'] = (targetKey, action) => {
        // console.log('执行了', tabList);
        // setTabList(tabList.filter(item => item.tab !== '/login'));
        if (action === 'remove') {
            if (tabList.length <= 1) return;
            if (targetKey === active) {
                let index = tabList.findIndex((tab) => tab.tab === targetKey);
                if (index === 0) {
                    index = 1;
                } else {
                    index -= 1;
                }
                resetTabToOther(tabList[index]?.tab);
            }
            console.log(tableCacheRef, targetKey, '这是个啥');
            tableCacheRef.current.delete(targetKey);
            setTabList(tabList.filter((tab) => tab.tab !== targetKey));
        }
    };

    const resetTabToOther = (target: string) => {
        console.log(target, '标签跳转');
        history.push(target);
        setActive(target);
    };

    useEffect(() => {
        if (!user) {
            history.push('/login');
        }
        const map = tableCacheRef.current;
        const has = map.has(pathname);
        setActive(pathname);
        if (has) return;
        map.set(pathname, props.children);
        // console.log(tabList, '====')
        if (pathname !== '/login') {
            setTabList([...tabList, { tab: pathname, title: document.title }]);
        }
    }, [pathname]);
    if (isIndenpendentRoute) return props.children;
    return (
        <ProLayout
            fixedHeader={true}
            navTheme="light"
            menuHeaderRender={() => (
                <div
                    style={{
                        width: '100%',
                        display: 'flex',
                        flexFlow: 'column wrap',
                        textAlign: 'center',
                        alignContent: 'center',
                    }}
                >
                    <span
                        style={{ fontSize: 16, color: '#333', fontWeight: 600 }}
                    >
                        后台管理
                    </span>
                    <span style={{ fontSize: 12, color: '#999' }}>
                        军工项目借书还书
                    </span>
                </div>
            )}
            headerContentRender={() => <Header />}
            collapsedButtonRender={false}
            collapsed={false}
            fixSiderbar
            breadcrumbRender={(routers = []) => {
                if (routers.length > 0) {
                    return [{ path: '/', breadcrumbName: '首页' }, ...routers];
                }
            }}
            style={{ height: '100%' }}
            route={{ path: '/', routes }}
            menuItemRender={(item, dom) => {
                return <NavLink to={item.path!}>{dom}</NavLink>;
            }}
            itemRender={(route) => (
                // <NavLink to={route.path} key={props.location.key}>{route.breadcrumbName}</NavLink>
                <NavLink to={route.path}>{route.breadcrumbName}</NavLink>
            )}
        >
            <PageTabActionContext.Provider
                value={{
                    removeCurrentTab: () => {
                        console.log(active, '这是什么');
                        if (!active) return;
                        removeTabHandler(active, 'remove');
                    },
                }}
            >
                <Tabs
                    type="editable-card"
                    tabBarGutter={0}
                    activeKey={active}
                    hideAdd
                    onChange={(active) => {
                        resetTabToOther(active);
                    }}
                    onEdit={removeTabHandler}
                >
                    {tabList.map((item) => {
                        // console.log(item, 123123)
                        return (
                            <Tabs.TabPane tab={item.title} key={item.tab}>
                                <PageContainer
                                    ghost
                                    title={false}
                                    breadcrumbRender={(props: any, dom) => {
                                        return (
                                            <div
                                                style={{
                                                    display: 'flex',
                                                    margin: '16px 0px 12px',
                                                }}
                                            >
                                                <span
                                                    style={{
                                                        marginRight: '16px',
                                                        fontSize: '16px',
                                                    }}
                                                >
                                                    {props.pageTitleInfo.title}
                                                </span>
                                                {dom}
                                            </div>
                                        );
                                    }}
                                >
                                    {renderChildren(item)}
                                </PageContainer>
                            </Tabs.TabPane>
                        );
                    })}
                </Tabs>
            </PageTabActionContext.Provider>
        </ProLayout>
    );
}
export default Index;
